package com.jz.community.moduleshopping.address.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.view.DividerItemDecoration;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.address.adapter.NearShopListAdapter;
import com.jz.community.moduleshopping.address.bean.BaseAddressInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.ShopSelfAddressInfo;
import com.jz.community.moduleshopping.confirmOrder.task.GetShopSelfAddressTask;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony.Fan on 2018/5/3 09:37
 * <p>
 * 自提点列表
 */
public class SelfAddressListActivity extends BaseMvpActivity {
    @BindView(R2.id.tv_back)
    ImageView tvBack;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.commit_order_toolbar)
    Toolbar commitOrderToolbar;
    @BindView(R2.id.rv_choose_server_point)
    RecyclerView rvChooseServerPoint;
    @BindView(R2.id.search_near_pickup_iv)
    ImageView searchNearPickupIv;
    @BindView(R2.id.search_address_et)
    EditText searchAddressEt;
    @BindView(R2.id.search_cancel_tv)
    TextView searchCancelTv;
    @BindView(R2.id.search_address_et_layout)
    RelativeLayout searchAddressEtLayout;
    @BindView(R2.id.view_line_tv)
    TextView viewLineTv;
    private ShopSelfAddressInfo.EmbeddedBean selfAddressInfo;
    private NearShopListAdapter nearShopListAdapter;
    private LoadService loadService;
    private String shopId;
    private String lat;
    private String lon;
    private String selfType;
    private String keyWord;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_choose_server_point;
    }

    @Override
    protected void initView() {
        tvTitle.setText("选择自提点");
        SHelper.vis(searchAddressEtLayout, viewLineTv);
        setImmersionBar(commitOrderToolbar);
    }

    @Override
    protected void addListener() {
        loadService = LoadSir.getDefault().register(rvChooseServerPoint, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (loadService.getCurrentCallback() == ErrorCallback.class) {
                    initDatas();
                }
            }
        });

        loadService.setCallBack(EmptyCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                ImageView mIvEmpty = view.findViewById(R.id.empty_img);
                TextView mTvEmpty = view.findViewById(R.id.empty_tv);
                mIvEmpty.setImageResource(R.mipmap.ic_address_empty);
                mTvEmpty.setText("暂无自提点！");
            }
        });

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        searchAddressEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if (Preconditions.isNullOrEmpty(keyWord)) {
                        return true;
                    }

                    getShopSelfAddress(shopId, lat, lon, selfType, keyWord);

                }
                return false;
            }
        });

        searchNearPickupIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SHelper.vis(searchAddressEtLayout, viewLineTv);
            }
        });

        searchCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SHelper.gone(searchAddressEtLayout, viewLineTv);
                initNearShopListAdapter(selfAddressInfo);
            }
        });
        selfAddressChangeEvents();
    }

    @SuppressLint("CheckResult")
    private void selfAddressChangeEvents() {
        RxTextView.textChangeEvents(searchAddressEt)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<TextViewTextChangeEvent>() {
                    @Override
                    public void accept(TextViewTextChangeEvent onTextChangeEvent) throws Exception {
                        keyWord = onTextChangeEvent.text().toString().trim();

                        if (Preconditions.isNullOrEmpty(keyWord)) {
                            return;
                        }
                        getShopSelfAddress(shopId, lat, lon, selfType, keyWord);
                    }
                });
    }

    @Override
    protected void initDatas() {
        selfAddressInfo = (ShopSelfAddressInfo.EmbeddedBean) getIntent().getSerializableExtra("selfAddress");
        shopId = getIntent().getStringExtra("shopId");
        lat = getIntent().getStringExtra("lat");
        lon = getIntent().getStringExtra("lon");
        selfType = getIntent().getStringExtra("selfType");
        if (!Preconditions.isNullOrEmpty(selfAddressInfo) && !Preconditions.isNullOrEmpty(selfAddressInfo.getContent())) {
            loadService.showSuccess();
            initNearShopListAdapter(selfAddressInfo);
        } else {
            loadService.showCallback(EmptyCallback.class);
        }
        showSelfSearchUI();
    }

    private void showSelfSearchUI() {
        SHelper.vis(searchNearPickupIv);
    }


    /**
     * 搜索自提点
     *
     * @param shopId
     * @param lat
     * @param lon
     * @param type
     */
    private void getShopSelfAddress(String shopId, String lat, String lon, String type, String kayWord) {
        new GetShopSelfAddressTask(this, o -> {
            ShopSelfAddressInfo shopSelfAddressInfo = (ShopSelfAddressInfo) o;
            if (!Preconditions.isNullOrEmpty(shopSelfAddressInfo)) {
                initNearShopListAdapter(shopSelfAddressInfo.get_embedded());
            }
        }).execute(shopId, lon, lat, type, kayWord);
    }

    /**
     * 附近自提列表
     */
    private void initNearShopListAdapter(ShopSelfAddressInfo.EmbeddedBean selfAddressInfo) {
        if (!Preconditions.isNullOrEmpty(selfAddressInfo) && !Preconditions.isNullOrEmpty(selfAddressInfo.getContent())) {
            LinearLayoutManager goods_layoutManager = new LinearLayoutManager(this);
            rvChooseServerPoint.setHasFixedSize(true);
            rvChooseServerPoint.setFocusable(false);
            rvChooseServerPoint.setLayoutManager(goods_layoutManager);
            rvChooseServerPoint.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            nearShopListAdapter = new NearShopListAdapter(R.layout.module_shopping_item_near_shop_list, selfAddressInfo.getContent(), "2");
            rvChooseServerPoint.setAdapter(nearShopListAdapter);
            nearShopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intent = new Intent();
                    intent.putExtra("isSelf", false);
                    intent.putExtra("address", nearShopListAdapter.getData().get(position).getAddress());
                    intent.putExtra("mentionName", nearShopListAdapter.getData().get(position).getName());
                    intent.putExtra("tel", nearShopListAdapter.getData().get(position).getContact_tel());
                    intent.putExtra("distance", nearShopListAdapter.getData().get(position).getDistance());
                    intent.putExtra("cityCode", nearShopListAdapter.getData().get(position).getCityCode());
                    intent.putExtra("mentionId", ConverterUtils.toString(nearShopListAdapter.getData().get(position).getId()));
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

}
